package com.grz.springbootdemo.controller;

import com.grz.springbootdemo.core.HasUsername;
import com.grz.springbootdemo.core.Result;
import com.grz.springbootdemo.domain.User;
import com.grz.springbootdemo.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@AllArgsConstructor
@RequestMapping("/user")
public class UserController {

    private final IUserService userService;

    @PostMapping
    public Result<Integer> insert(@RequestBody User user){
        // 插入之前，需要做参数校验
        return Result.success(userService.insert(user));
    }

    // 自定义规则：是admin用户才能修改Book
    @HasUsername(value = "admin")
    @PutMapping
    public Result<Integer> update(@RequestBody User user) {
        if (user.getId() == null) {
            return Result.error(400, "请传入id的参数");
        }
        return Result.success(userService.update(user));
    }

    @DeleteMapping
    public Result<Integer> delete(int id) {
        return Result.success(userService.delete(id));
    }

    @GetMapping("/{id}")
    public Result<User> selectById(@PathVariable int id) {
        int i = 1 / 0;
        return Result.success(userService.selectById(id));
    }

    @PostMapping("/list")
    public Result<List<User>> selectList(@RequestBody User user) {
        return Result.success(userService.selectList(user));
    }
}
